import { useAssistants } from '@renderer/hooks/useAssistant'
import { useSettings } from '@renderer/hooks/useSettings'
import { exitTemporaryTopic, TopicManager, useActiveTopic } from '@renderer/hooks/useTopic'
import NavigationService from '@renderer/services/NavigationService'
import { useAppDispatch } from '@renderer/store'
import { Assistant } from '@renderer/types'
import { FC, useEffect, useRef, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import styled from 'styled-components'

import Chat from './Chat'
import Navbar from './Navbar'
import HomeTabs from './Tabs'

let _activeAssistant: Assistant

const HomePage: FC = () => {
  const { assistants } = useAssistants()
  const navigate = useNavigate()
  const dispatch = useAppDispatch()

  const location = useLocation()
  const state = location.state

  const [activeAssistant, setActiveAssistant] = useState(state?.assistant || _activeAssistant || assistants[0])
  const { activeTopic, setActiveTopic } = useActiveTopic(activeAssistant, state?.topic)
  const {
    showAssistants,
    showTopics,
    topicPosition,
    temporaryTopicMode,
    temporaryTopicId,
    temporaryTopicAssistantId,
    setTemporaryTopicMode,
    setTemporaryTopicId,
    setTemporaryTopicAssistantId
  } = useSettings()

  _activeAssistant = activeAssistant

  useEffect(() => {
    NavigationService.setNavigate(navigate)
  }, [navigate])

  useEffect(() => {
    state?.assistant && setActiveAssistant(state?.assistant)
    state?.topic && setActiveTopic(state?.topic)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state])

  // 监听路由变化，当离开主页时自动退出当前助手下的临时话题模式
  useEffect(() => {
    const isHomePage = location.pathname === '/'
    if (!isHomePage && temporaryTopicMode && temporaryTopicId && temporaryTopicAssistantId) {
      const assistant = assistants.find((a) => a.id === temporaryTopicAssistantId)
      if (assistant) {
        exitTemporaryTopic(assistant, temporaryTopicId, setTemporaryTopicMode, setTemporaryTopicId, dispatch)
        setTemporaryTopicAssistantId(null)
      }
    }
  }, [
    location.pathname,
    temporaryTopicMode,
    temporaryTopicId,
    temporaryTopicAssistantId,
    assistants,
    dispatch,
    setTemporaryTopicMode,
    setTemporaryTopicId,
    setTemporaryTopicAssistantId
  ])

  // 监听话题变化，如果切换到非临时话题，则退出临时话题模式
  const prevTopicIdRef = useRef(activeTopic?.id)

  useEffect(() => {
    if (activeTopic) {
      // 如果话题ID变化了
      if (prevTopicIdRef.current !== activeTopic.id) {
        prevTopicIdRef.current = activeTopic.id
      }
    }
  }, [activeTopic])

  useEffect(() => {
    const canMinimize = topicPosition == 'left' ? !showAssistants : !showAssistants && !showTopics
    window.api.window.setMinimumSize(canMinimize ? 520 : 1080, 600)

    return () => {
      window.api.window.resetMinimumSize()
      // 组件卸载时只清理临时话题的消息文件，不从Redux状态中移除临时话题
      if (temporaryTopicMode && temporaryTopicId) {
        TopicManager.cleanupTemporaryTopic(temporaryTopicId)
      }
    }
  }, [showAssistants, showTopics, topicPosition, temporaryTopicMode, temporaryTopicId])

  // 切换助手时自动关闭当前助手下的临时话题
  const prevAssistantRef = useRef(activeAssistant)
  useEffect(() => {
    if (temporaryTopicMode && temporaryTopicId && temporaryTopicAssistantId) {
      const assistant = assistants.find((a) => a.id === temporaryTopicAssistantId)
      if (assistant) {
        exitTemporaryTopic(assistant, temporaryTopicId, setTemporaryTopicMode, setTemporaryTopicId, dispatch)
        setTemporaryTopicAssistantId(null)
      }
    }
    prevAssistantRef.current = activeAssistant
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeAssistant])

  if (!activeTopic) return null

  return (
    <Container id="home-page">
      <Navbar activeAssistant={activeAssistant} setActiveTopic={setActiveTopic} />
      <ContentContainer id="content-container">
        {showAssistants && (
          <HomeTabs
            activeAssistant={activeAssistant}
            activeTopic={activeTopic}
            setActiveAssistant={setActiveAssistant}
            setActiveTopic={setActiveTopic}
            position="left"
          />
        )}
        <Chat
          assistant={activeAssistant}
          activeTopic={activeTopic}
          setActiveTopic={setActiveTopic}
          setActiveAssistant={setActiveAssistant}
        />
      </ContentContainer>
    </Container>
  )
}

const Container = styled.div`
  display: flex;
  flex: 1;
  flex-direction: column;
  max-width: calc(100vw - var(--sidebar-width));
`

const ContentContainer = styled.div`
  display: flex;
  flex: 1;
  flex-direction: row;
  overflow: hidden;
`

export default HomePage
